package com.orange.off.cloud.cloudoff.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.orange.off.cloud.cloudoff.R;
import com.orange.off.cloud.cloudoff.activity.IntermediaryActivity;
import com.orange.off.cloud.cloudoff.app.MyApplication;
import com.orange.off.cloud.cloudoff.events.ChangePassword2Event;
import com.orange.off.cloud.cloudoff.events.PersonalUpdateInformationEvent;
import com.orange.off.cloud.cloudoff.events.PersonalUpdateNameEvent;
import com.orange.off.cloud.cloudoff.model.UploadResponse;
import com.orange.off.cloud.cloudoff.urls.AppUrls;
import com.orange.off.cloud.cloudoff.utils.GlideImageLoader;
import com.orange.off.cloud.cloudoff.utils.Options;
import com.orange.off.cloud.cloudoff.utils.ToastUtils;
import com.orange.off.cloud.cloudoff.views.CircleImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

/**
 * 个人中心------个人信息（头像）
 *
 * @author smile
 */
public class PersonalInformationFragment extends Fragment {


    @Bind(R.id.img_personalAvatar)
    CircleImageView imgPersonalAvatar;
    @Bind(R.id.tv_personalName)
    TextView tvPersonalName;
    @Bind(R.id.relativeLayout_name)
    RelativeLayout relativeLayoutName;
    @Bind(R.id.tv_personalTel)
    TextView tvPersonalTel;
    @Bind(R.id.relativeLayout_password)
    RelativeLayout relativeLayoutPassword;
    @Bind(R.id.rt_profileBack)
    RelativeLayout rtProfileBack;
    private DisplayImageOptions options;
    private ImagePicker imagePicker;
    private String personalName="";
    public static PersonalInformationFragment newInstance(Bundle bundle) {
        PersonalInformationFragment fragment = new PersonalInformationFragment();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        initViews();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.myprofilefragment, container, false);
        ButterKnife.bind(this, view);
        return view;
    }


    private void initViews() {
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());
        options = Options.getHeaderOptions();
        ImageLoader.getInstance().displayImage(getArguments().getString("headerPic"), imgPersonalAvatar, options);
        personalName=getArguments().getString("personalName");
        tvPersonalName.setText(personalName);
        tvPersonalTel.setText(getArguments().getString("personalPhone"));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                //                showProgressDialog("头像上传中...");
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                Log.d(MyApplication.DEBUG, "头像路径----》" + images.get(0).path);
                ImageLoader.getInstance().displayImage("file://" + images.get(0).path, imgPersonalAvatar);
                File file = new File(images.get(0).path);
                Log.d(MyApplication.DEBUG, "头像生成路径----》" + file.getPath());
                RequestParams params = new RequestParams();//请求参数
                params.addFormDataPart("aid", MyApplication.aid);
                params.addFormDataPart("image", file);
                params.addFormDataPart("name", personalName);
                HttpRequest.post(AppUrls.UpdateInformation, params, new BaseHttpRequestCallback<UploadResponse>() {
                    @Override
                    public void onSuccess(UploadResponse uploadResponse) {
                        super.onSuccess(uploadResponse);
                        Log.d(MyApplication.DEBUG, "Upload---->" + uploadResponse.getData());
                        if (uploadResponse.getSuccess()) {
                            ToastUtils.show(getActivity(), "头像上传成功", Toast.LENGTH_SHORT);
                            EventBus.getDefault().post(new PersonalUpdateInformationEvent(true));
                        } else {
                            ToastUtils.show(getActivity(), uploadResponse.getMessage(), Toast.LENGTH_SHORT);
                        }

                    }

                    @Override
                    public void onFailure(int errorCode, String msg) {
                        super.onFailure(errorCode, msg);
                    }

                    @Override
                    public void onProgress(int progress, long networkSpeed, boolean done) {
                    }
                });
            } else {
                ToastUtils.show(getActivity(), "没有数据");
            }
        }
    }
    @OnClick({R.id.img_personalAvatar, R.id.relativeLayout_name, R.id.relativeLayout_password})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_personalAvatar:
                //修改头像，不跳页面：
                imagePicker.setMultiMode(false);//单选
                imagePicker.setShowCamera(true);//显示相机
                imagePicker.setCrop(true);//裁剪
                //-----------------------------------------------------------------------------------------
                imagePicker.setSaveRectangle(true);//是否按照矩形区域保存图片
                imagePicker.setStyle(CropImageView.Style.RECTANGLE);
                Integer width = 280;//界面矩形宽
                Integer height = 280;//界面矩形高
                width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, width, getResources().getDisplayMetrics());
                height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, height, getResources().getDisplayMetrics());
                imagePicker.setFocusWidth(width);
                imagePicker.setFocusHeight(height);
                //------------------------------以上区域是图片裁剪设置-------------------------------------------
                imagePicker.setOutPutX(800);//裁剪后宽度
                imagePicker.setOutPutY(800);//裁剪后高度
                Intent intent = new Intent(getActivity(), ImageGridActivity.class);
                startActivityForResult(intent, 100);
                break;
            case R.id.relativeLayout_name:
                //修改姓名：
                Intent nameIntent = new Intent(getActivity(), IntermediaryActivity.class);
                nameIntent.putExtra("type", IntermediaryActivity.CHANGENAME);
                nameIntent.putExtra("personalName", personalName);
                startActivity(nameIntent);
                break;
            case R.id.relativeLayout_password:
                //修改密码：
                Intent pwdIntent = new Intent(getActivity(), IntermediaryActivity.class);
                pwdIntent.putExtra("type", IntermediaryActivity.CHANGEPWD);
                startActivity(pwdIntent);
                break;
        }
    }
    /**
     * EventBus：姓名修改成功事件通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onInformationUpdateEvent(PersonalUpdateNameEvent event) {
        tvPersonalName.setText(event.personalName);
    }
    /**
     * EventBus：密码修改成功事件通知(关闭该界面重新登录)
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdatePwd2Event(ChangePassword2Event event) {
        getActivity().finish();
    }
    @OnClick(R.id.rt_profileBack)
    public void onClick() {
        getActivity().finish();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            getActivity().finish();
            return true;
        }
        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }
}
